<?php
class BaseController extends Yaf_Controller_Abstract {

    const DES_KEY = 'piano';
    const USER_LOGIN_STATUS = '_USER_LOGIN_STATUS';
    public $DES_KEY_ARR = array(
            'ar'=>'pianoar', 
            'ip'=>'pianoip',
            'pc'=>'pianopc',
        );
    protected $_params;
    protected $_ispost;
    protected $_isget;
    protected $_requestdata_f = '';

    public function init()
    {
        $request = $this->getRequest();
        /** 获取请求方法 */
        $this->_isget= $request->isGet();
        $this->_ispost = $request->isPost();
        /** 获取所有参数 */
        $get_data = $request->getQuery();
        $post_data = $request->getPost();
        $request_data = array_merge($get_data, $post_data);
        if (isset($request_data['f'])) $this->_requestdata_f = $request_data['f'];
        $request_data = $this->is_des($request_data);
        $this->_params = (new ParamPackTool($request_data));
        /** 记录请求日志 */
        LogTool::requestdataLog()->log(json_encode($request_data));
        /** 禁用模板输出 */
        Yaf_Dispatcher::getInstance()->disableView();
    }

    /**
     * 判断请求是否为get
     * @throws YExceptionTool
     */
    protected function isGet()
    {
        if ( !$this->_isget ) throw new YExceptionTool(YExceptionTool::METHOD_MUST_GET);
    }

    /**
     * 判断请求是否为post
     * @throws YExceptionTool
     */
    protected function isPost()
    {
//        if ( !$this->_ispost ) throw new YExceptionTool(YExceptionTool::METHOD_MUST_POST);
        if ( !$this->_ispost ){
            return false;
        }else{
            return true;
        }
    }

    protected function setResponseHeader()
    {/*{{{*/
        $response = $this->getResponse();
        $response->setHeader("Access-Control-Allow-Origin","*");
    }/*}}}*/

    /**
     * 返回加密
     * @param $request_data
     * @return mixed
     */
    protected function des_encode_msg($request_data)
    {
        if (in_array($this->_requestdata_f, array('ar', 'ip', 'pc')))
        {
            $key = $this->_params->getSx() ? : $this->DES_KEY_ARR[$this->_requestdata_f] ;
            return des_encode_msg($key, $request_data);
        }
        return $request_data;
    }

    /**
     * 是否解密
     * @param array $request_data
     * @return mixed
     * @throws YExceptionTool
     */
    private function is_des($request_data = array())
    {
        if (in_array($this->_requestdata_f, array('ar', 'ip', 'pc')))
        {
            if (!isset($request_data['q'])) throw new YExceptionTool(YExceptionTool::Q_PARAMPACK_ERROR);
            $request_data = json_decode(des_decode_msg($this->DES_KEY_ARR[$this->_requestdata_f], $request_data['q']), true);
        }
        return $request_data;
    }

    protected function response_redis($key)
    {
        $_redisTool = RedisTool::getInstance();
        $res = $_redisTool->get($key);
        if (!$res) return true;
        LogTool::responsesuccLog()->log($res);
        echo $this->des_encode_msg($res);
    }
    
    /**
     * 验证登录
     * @param type $uid
     * @return boolean
     */
    public function checkLogin( $uid = 0 ) {
        $redis = RedisTool::getInstance();
        $cookie = $_COOKIE['USELF'];
        if( $uid ){
            $ua = $this->getUa();
            if( md5($ua).$uid."LOGIN" == $cookie ){
                return $uid;
            }
        }
        $token = $redis->get( base64_decode( $cookie ) );
        if (!$token) {
            return false;
        }else{
            return $token;
        }
    }
    
    /**
     * 增加阅读记录
     */
    public function addRecord( $novelid , $chapterid )
    {
        $record = $this->getRecord();
        $now = time();
        $sign = array( $novelid.'_'.$chapterid , $now );
        $r = [];
        if( !$record ){
            $arr = array ();
            $arr[] = $sign;
            $rec = json_encode( $arr );
        }else{
            $rec_k_v = array_column ( $record , null , 'novelid' );
            if( isset( $rec_k_v[ $novelid ] ) ){
                if( $rec_k_v[ $novelid ][ 'chapterid' ] <=  $chapterid ){
                    unset( $rec_k_v[ $novelid ] );
                    $r = [
                        'novelid'   => $novelid,
                        'chapterid' => $chapterid,
                        'time'      => $now,
                    ];
                    array_unshift( $rec_k_v , $r );
                }
            }else{
                $r = [
                    'novelid'   => $novelid,
                    'chapterid' => $chapterid,
                    'time'      => $now,
                ];
                array_unshift( $rec_k_v , $r );
            }
            $res = [];
            foreach($rec_k_v as $val){
                $res[] = array( $val['novelid'].'_'.$val['chapterid'] , $val['time'] );
            }
            $rec = json_encode( $res );
        }
        
        $uid = $this->checkLogin();
        if( $uid ){
            $redis = RedisTool::getInstance();
            $redis->set( $uid."READ_RECORD" , $rec );
        }
        setCookie( 'MYRECORD' , $rec , time()+3600*24*365 , '/' , '' , false , true );
    }
    
    /**
     * 获取阅读记录
     */
    public function getRecord()
    {
        $res = [];
        $uid = $this->checkLogin();
        if( $uid ){
            $redis = RedisTool::getInstance();
            $record = $redis->get( $uid."READ_RECORD");
            if(!$record){
                $record = $_COOKIE['MYRECORD'];
            }
        }else{
            $record = $_COOKIE['MYRECORD'];
        }
        
        if( $record ){
            $rec = json_decode( $record , true );
            foreach( $rec as $v ){
                $ids = explode('_', $v[0]);
                $res[] = [
                    'novelid'   => $ids[0],
                    'chapterid' => $ids[1],
                    'time'      => $v[1],
                ];
            }
        }
        return $res;
    }
    
    /**
     * 删除阅读记录
     */
    public function delRecords( $novelid = 0 , $uid = 0 )
    {
        if( !$novelid ){
            return false;
        }
        $records = $this->getRecord();
        $rec = array_column ( $records , null , 'novelid' );
        unset($records);
        
        foreach( $novelid as $id ){
            if( isset( $rec[ $id ] ) ){
                unset( $rec[ $id ] );
            }
        }
        
        $new_record = [];
        foreach( $rec as $v ){
            $new_record[] = array ( $v['novelid']."_".$v['chapterid'] , $v['time'] );
        }
        
        if( $uid ){
            $redis = RedisTool::getInstance();
            if( !empty( $new_record ) ){
                $redis->set( $uid."READ_RECORD" , json_encode($new_record) );
                setCookie( 'MYRECORD' , json_encode($new_record) , time()+3600*24*365 , '/' , '' , false , true );
            }else{
                $redis->delete( $uid."READ_RECORD" );
                setCookie( 'MYRECORD' , null , time()-3600 , '/' , '' , false , true );
            }
        }
        
        return true;
    }
    
    /**
     * 获取用户ip
     */
    public function getIp(){
        
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
            $ip = getenv("HTTP_CLIENT_IP");
        }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
            $ip = getenv("REMOTE_ADDR");
        }else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
            $ip = $_SERVER['REMOTE_ADDR'];
        }else{
            $ip = "unknown";
        }
        
        return $ip;
    } 
    
    /**
     * 获取用户浏览器
     */
    public function getUa()
    {
        $agent = $_SERVER['HTTP_USER_AGENT'];
        return $agent;
    }
    
    /**
     * 游客登入
     */
    public function addVisitor()
    {
        $ua = $this->getUa();
        $ip = $this->getIp();
        $visitor_cookie = $_COOKIE[ 'VISITOR' ];
        if( !$visitor_cookie ){
            $visit_dao = new Dao_VisitModel();
            $visitor   = $visit_dao->getVisitor( array( 'visit_ip' => $ip , 'visit_ua' => $ua ) );
            $now = date('Y-m-d H:i:s');
            if($visitor){
                $visit_dao->editVisitor( array( 'last_login_time' => $now ) , array( [ 'visit_ip' , $ip ] , [ 'visit_ua' , $ua ] ) );
            }else{
                $new_data  =  [];
                $new_data['vist_name'] = md5($ip.$ua);
                $new_data['partner_id'] = 0;
                $new_data['channel_id'] = 0;
                $new_data['last_login_time'] = $now;
                $new_data['come_from'] = '';
                $new_data['visit_ip'] = $ip;
                $new_data['visit_ua'] = $ua;
                $new_data['vist_time'] = $now;
                $visit_dao->addVisitor( $new_data );
            }
            setcookie( 'VISITOR' , md5($ip.$ua) , 0 , '/' );
        }
    }
    
}